package com.supermap.dataservice.mongodb.service;

import com.mongodb.gridfs.GridFSDBFile;
import com.supermap.dataservice.mongodb.repository.FileRepository;
import com.supermap.dataservice.mongodb.MongoDbFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 
* @ClassName: FileServiceImpl 
* @Description: mongodb 文件存储逻辑实现
* @author yuyao
* @date 2018年1月8日 下午2:27:20
 */
@Service
public class FileService {
	
	@Autowired
	public FileRepository fileRepository;
	
	@Autowired
	private MongoTemplate mongoTemplate;
	
	@Autowired
	GridFsTemplate gridFsTemplate;

	/**
	 * 保存文件
	 * @param file MogDbFile
	 * @return
	 */
	public void saveFile(MongoDbFile file) {
		mongoTemplate.insert(file);
	}
	
	/**
	 * 
	* @Title: saveGridFile 
	* @Description: 大文件存储
	* @param @param file
	* @param @return
	* @param @throws IOException    设定文件 
	* @throws
	 */
	public void saveGridFile(MultipartFile file) throws IOException {
	    
		gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(), file.getContentType());
	   
	}
	
	
	/**
	 * 删除文件
	 * @param id MogDbFile
	 * @return
	 */
	public void removeFile(String id) {
		fileRepository.delete(id);
	}
	
	/**
	 * 根据id获取文件
	 * @param id MogDbFile
	 * @return
	 */
	public MongoDbFile getFileById(String id) {
		return fileRepository.findOne(id);
	}
	/**
	 * 
	* @Title: getGridFileById 
	* @Description: 通过ID 获取大文件
	* @param @param id
	* @param @return    设定文件 
	* @return MogDbFile    返回类型 
	* @throws
	 */
	public MongoDbFile getGridFileById(String id) {
		Query query = new Query();
	    query.addCriteria(Criteria.where("id").is(id));
		GridFSDBFile result = gridFsTemplate.findOne(query);
		try {
			result.writeTo(new File("C:\\Users\\MACHENIKE\\Desktop\\test\\" + result.getFilename()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	/**
	 * 分页查询，按上传时间降序
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	public List<MongoDbFile> listFilesByPage(int pageIndex, int pageSize) {
		Page<MongoDbFile> page = null;
		List<MongoDbFile> list = null;
		
		Sort sort = new Sort(Direction.DESC,"uploadDate"); 
		Pageable pageable = new PageRequest(pageIndex, pageSize, sort);
		
		page = fileRepository.findAll(pageable);
		list = page.getContent();
		return list;
	}
}
